<template>
  <el-drawer
    title="标签体系设计"
    size="60%"
    :visible.sync="drawerVisible"
    direction="rtl"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    :destroy-on-close="true"
    :before-close="beforeClose"
    @closed="clearDialog"
    custom-class="tag-drawer catalog-category-drawer"
    v-drawerResize
  >
    <div class="drawer-wrap">
      <div class="drawer-content tag-scrollbar">
        <el-col :span="8" class="category-tree" v-loading="loading">
          <el-col :span="20">
            <el-input v-model="search" placeholder="请输入搜索内容" @keyup.enter.native="searchFun">
              <i slot="suffix" class="el-input__icon el-icon-close" @click="clearSearch"></i>
            </el-input>
          </el-col>
          <el-col :span="4" class="refresh-box"><i class="el-icon-refresh" @click="getList()"></i></el-col>
          <el-col :span="24" class="category-tree-content">
            <el-tree
              ref="categoryTree"
              :data="dataList"
              :props="props"
              :expand-on-click-node="false"
              highlight-current
              default-expand-all
              :filter-node-method="filterNode"
              @node-click="nodeClick"
            >
              <div
                class="category-tree-item clearfix"
                :class="{ select: selectData.id === data.catalogId }"
                slot-scope="{ node, data }"
              >
                <el-tooltip effect="dark" :content="node.label" placement="top">
                  <span class="category-name">{{ node.label }}</span>
                </el-tooltip>
                <span class="asset-count">{{ data.dataAssetCount }}</span>
                <span class="tree-button">
                  <!-- <el-tooltip effect="dark" content="查看编辑" placement="top" :enterable="false">
                    <i
                      v-if="data.parentCatalogId && data.catalogId"
                      class="el-icon-edit"
                      @click.stop="handleEdit(data)"
                    ></i>
                  </el-tooltip> -->
                  <el-tooltip effect="dark" content="新增子节点" placement="top" :enterable="false">
                    <i
                      v-if="!data.sysCatalog && (data.dataAssetCount === 0 || !data.tail)"
                      class="el-icon-circle-plus-outline"
                      @click.stop="nodeAdd(data)"
                    ></i>
                  </el-tooltip>
                  <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                    <i
                      v-if="
                        !data.sysCatalog &&
                          data.parentCatalogId &&
                          data.catalogId &&
                          data.dataAssetCount === 0 &&
                          data.tail
                      "
                      class="el-icon-delete"
                      @click.stop="handleDelete(data)"
                    ></i>
                  </el-tooltip>
                </span>
              </div>
            </el-tree>
          </el-col>
        </el-col>
        <el-col :span="16" class="category-edit">
          <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
            <div v-if="rootId === selectData.id">
              <el-form-item label="标签体系名称">
                <el-col :span="24">
                  <span>{{ editForm.name }}</span>
                </el-col>
                <el-col :span="24" class="catalog-tip">
                  <span>点击侧栏分类即可查看分类信息</span>
                </el-col>
              </el-form-item>
            </div>
            <div v-else>
              <div class="editForm-box">
                <el-form-item label="分类名称" v-if="!editForm.edit">
                  <span>{{ selectData.name }}</span>
                </el-form-item>

                <el-form-item label="分类描述" v-if="!editForm.edit">
                  <el-col :span="18">
                    <el-input
                      type="textarea"
                      :rows="3"
                      resize="none"
                      v-model="selectData.cmntStr"
                      maxlength="1000"
                      show-word-limit
                      readonly
                    >
                    </el-input>
                  </el-col>
                </el-form-item>

                <el-form-item label="分类名称：" prop="name" v-if="editForm.edit">
                  <el-col :span="12">
                    <el-input placeholder="请输入分类名称" v-model="editForm.name" ref="nameInput"></el-input>
                  </el-col>
                </el-form-item>

                <el-form-item label="分类描述：" prop="cmntStr" v-if="editForm.edit">
                  <el-col :span="18">
                    <el-input
                      type="textarea"
                      :rows="3"
                      placeholder="请在此输入你的描述，总长度不超过1000个字符"
                      resize="none"
                      v-model="editForm.cmntStr"
                    >
                    </el-input>
                  </el-col>
                </el-form-item>
                <span class="edit-box" @click="editMode" v-if="!editForm.edit && !selectData.sys">
                  <el-tooltip effect="dark" content="修改分类信息" placement="top" :enterable="false">
                    <i class="el-icon-edit"></i>
                  </el-tooltip>
                </span>
                <div class="edit-button" v-if="editForm.edit && !selectData.sys">
                  <el-button size="small" @click="editCancal" v-if="selectData.id">取消</el-button>
                  <el-button type="primary" size="small" @click="submit" :loading="loading">保存</el-button>
                </div>
              </div>

              <el-form-item label="父分类名称：" prop="pid">
                <span>{{ dataIds[selectData.pid] ? dataIds[selectData.pid].catalogNm : this.name }}</span>
              </el-form-item>

              <el-form-item label="分类层级：" prop="level">
                <span>{{ selectData.level }}</span>
              </el-form-item>
            </div>
          </el-form>
          <template v-if="catalogClassType !== 0 && selectData.level && $auth('pac:pacThirdCode:view')">
            <el-form :model="codeForm" label-width="110px" :rules="codeFormRules" ref="codeForm">
              <div class="code-wrap">
                <span class="code-btn">
                  <span class="edit-btn" @click="codeEditable = true">
                    <el-tooltip effect="dark" content="修改第三方编码" placement="top" :enterable="false">
                      <i class="el-icon-edit"></i>
                    </el-tooltip>
                  </span>
                  <span class="delete-btn" @click="deleteCode">
                    <el-tooltip effect="dark" content="删除第三方编码" placement="top" :enterable="false">
                      <i class="el-icon-close"></i>
                    </el-tooltip>
                  </span>
                </span>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="第三方编码" prop="thirdPartyCode">
                      <template slot="label" v-if="codeEditable">
                        <span
                          >第三方编码<el-popover
                            effect="dark"
                            title="最新编码信息"
                            :content="codeInfo.lastCode || '暂无'"
                            placement="top"
                            trigger="hover"
                            @show="getLastCode"
                          >
                            <i class="el-icon-info" slot="reference"></i>
                          </el-popover>
                        </span>
                      </template>
                      <span v-if="!codeEditable">{{ codeInfo.thirdPartyCode || '暂无' }}</span>
                      <el-input placeholder="请输入第三方编码" v-model="codeForm.thirdPartyCode" v-else></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="编码映射描述" prop="codeDesc">
                      <span v-if="!codeEditable">{{ codeInfo.codeDesc || '暂无' }}</span>
                      <el-input
                        placeholder="请输入编码映射描述"
                        v-model="codeForm.codeDesc"
                        type="textarea"
                        :rows="3"
                        resize="none"
                        v-else
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-if="codeEditable">
                  <el-col align="right">
                    <el-button @click="cancelEditCode">取消</el-button>
                    <el-button type="primary" @click="submitCode">确定</el-button>
                  </el-col>
                </el-row>
              </div>
            </el-form>
          </template>
        </el-col>
      </div>
    </div>
    <div class="drawer-btns">
      <el-col :span="8" class="category-tree-button" v-if="$auth('front:handle:import:base')">
        <el-button type="primary" size="medium" @click="handleDownload">模板下载</el-button>
        <el-button type="primary" size="medium" @click="handleImport">批量导入</el-button>
      </el-col>
      <el-button type="primary" size="medium" @click="beforeClose()">关闭窗口</el-button>
    </div>
    <category-import ref="categoryImport" @refresh="getList"></category-import>
  </el-drawer>
</template>

<script>
import utils from '@/plugins/utils'
import categoryImport from './category-import-item'
export default {
  components: {
    categoryImport
  },
  data() {
    var checkCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('第三方编码不能为空'))
      } else {
        let isAuth = true
        for (var i = 0; i < value.length; i++) {
          let n = value.charCodeAt(i)
          if (!((n >= 48 && n <= 57) || (n >= 65 && n <= 90) || (n >= 97 && n <= 122) || n === 95)) {
            isAuth = false
          }
        }
        if (!isAuth) {
          return callback(new Error('只能输入数字、字母或者下划线'))
        } else {
          return callback()
        }
      }
    }
    return {
      drawerVisible: false,
      id: '',
      name: '',
      catalogClassType: 0,
      dataList: [],
      dataIds: {},
      rootId: '',
      search: '',
      props: {
        children: '_children',
        label: 'catalogNm'
      },
      loading: false,
      selectData: {
        id: '',
        pid: '',
        level: 1,
        isLeaf: true,
        sys: false,
        name: '',
        cmntStr: ''
      },
      editForm: {
        edit: false,
        name: '',
        cmntStr: ''
      },
      editFormRules: {
        name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
          { max: 30, message: '分类名称不能超过30个字符', trigger: 'blur' }
        ],
        cmntStr: [{ max: 1000, message: '分类描述不能超过1000个字符', trigger: 'blur' }]
      },
      codeEditable: false,
      codeInfo: {
        thirdPartyCode: '',
        codeDesc: '',
        lastCode: ''
      },
      codeForm: {
        thirdPartyCode: '',
        codeDesc: ''
      },
      codeFormRules: {
        thirdPartyCode: [{ validator: checkCode, trigger: 'blur' }]
      }
    }
  },
  methods: {
    showDrawer(params) {
      this.id = params.id
      this.name = params.name
      this.catalogClassType = params.catalogClassType
      this.getList(true)
      this.drawerVisible = true
    },
    getList(reset) {
      this.$ajax({
        url: this.$ajax.setUrl(`dcl/dclAssetCatalog/catalogClassId/${this.id}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          var list = utils.arrayToTree(data.data, {
            id: 'catalogId',
            pid: 'parentCatalogId',
            mainSort: 'catalogLevel'
          })
          this.dataList = list
          this.setDataIds(data.data)
          if (reset) this.handleEdit(this.dataIds[this.rootId])
          this.$nextTick(() => {
            this.searchFun()
          })
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    setDataIds(data) {
      var ids = {}
      data.forEach(item => {
        ids[item.catalogId] = item
        if (item.parentCatalogId === 0) this.rootId = item.catalogId
      })
      this.dataIds = ids
    },
    searchFun() {
      this.$refs.categoryTree.filter(this.search)
    },
    clearSearch() {
      this.search = ''
      this.searchFun()
    },
    filterNode(value, data) {
      if (!value) return true
      return data.catalogNm.indexOf(value) !== -1
    },
    nodeClick(data) {
      if (this.editForm.edit) {
        this.$confirm('当前窗口正在编辑中，确定要放弃修改吗？')
          .then(() => {
            this.handleEdit(data)
          })
          .catch(() => {})
      } else {
        this.handleEdit(data)
      }
    },
    nodeAdd(data) {
      if (this.editForm.edit) {
        this.$confirm('当前窗口正在编辑中，确定要放弃修改吗？')
          .then(() => {
            this.handleAdd(data)
          })
          .catch(() => {})
      } else {
        this.handleAdd(data)
      }
    },
    handleEdit(data) {
      this.selectData = {
        id: data.catalogId,
        pid: data.parentCatalogId,
        level: data.catalogLevel,
        isLeaf: data.tail,
        sys: !!data.sysCatalog,
        name: data.catalogNm,
        cmntStr: data.catalogDesc
      }
      this.editForm = {
        edit: false,
        name: data.catalogNm,
        cmntStr: data.catalogDesc
      }
      this.$refs.editForm && this.$refs.editForm.clearValidate()
      if (this.catalogClassType !== 0 && this.selectData.level && this.$auth('pac:pacThirdCode:view'))
        this.getThirdCode()
    },
    handleAdd(data) {
      this.selectData = {
        id: '',
        pid: data.catalogId,
        level: data.catalogLevel + 1,
        isLeaf: true,
        sys: false,
        name: '',
        cmntStr: ''
      }
      this.editForm = {
        edit: true,
        name: '',
        cmntStr: ''
      }
      this.$refs.editForm && this.$refs.editForm.clearValidate()
      this.$nextTick(() => this.$refs.nameInput && this.$refs.nameInput.focus())
    },
    handleDelete(item) {
      this.$confirm('确认删除【' + item.catalogNm + '】？')
        .then(() => {
          let messageBox = document.getElementsByClassName('el-message-box__wrapper')
          messageBox[0].focus() // 防止按空格键重复确定
          this.$ajax({
            url: this.$ajax.setUrl(`dcl/dclAssetCatalog/${item.catalogId}`),
            method: 'delete',
            params: this.$ajax.setParams()
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.getList(item.catalogId === this.selectData.id || item.catalogId === this.selectData.pid)
              this.$message.success('操作成功')
              this.deleteThirdCode(item)
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        })
        .catch(() => {})
    },
    deleteThirdCode(item) {
      this.$ajax({
        url: this.$ajax.setUrl(`pac/${this.catalogClassType}/${item.catalogId}`),
        method: 'delete',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          // 删除第三方编码成功
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    editMode() {
      this.editForm.edit = true
    },
    editCancal() {
      this.editForm.edit = false
      this.editForm.name = this.selectData.name
      this.editForm.cmntStr = this.selectData.cmntStr
    },
    submit() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          let params = {
            catalogNm: this.editForm.name,
            catalogDesc: this.editForm.cmntStr
          }
          let ajaxType = ''
          if (this.selectData.id) {
            ajaxType = 'put'
            params.catalogId = this.selectData.id
          } else {
            ajaxType = 'post'
            params.catalogClassId = this.id
            if (this.selectData.pid) params.parentCatalogId = this.selectData.pid
          }
          this.$ajax({
            url: this.$ajax.setUrl('dcl/dclAssetCatalog'),
            method: ajaxType,
            data: this.$ajax.setData(params)
          })
            .then(({ data }) => {
              if (data && data.code === '0') {
                this.getList()
                this.editForm.edit = false
                this.selectData.name = this.editForm.name
                this.selectData.cmntStr = this.editForm.cmntStr
                if (this.selectData.id === '') this.selectData.id = data.data
                this.$message.success('操作成功')
              } else {
                this.$message.error(data.data || data.msg)
              }
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    submitCode() {
      this.$refs['codeForm'].validate(valid => {
        if (valid) {
          this.$ajax({
            url: this.$ajax.setUrl('pac'),
            method: 'post',
            data: this.$ajax.setData({
              codeType: this.catalogClassType,
              internalCode: this.selectData.id,
              thirdPartyCode: this.codeForm.thirdPartyCode,
              codeDesc: this.codeForm.codeDesc
            })
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.codeEditable = false
              this.getThirdCode()
              this.$message.success(data.msg)
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        }
      })
    },
    getThirdCode() {
      this.$ajax({
        url: this.$ajax.setUrl(`pac/catalog/${this.catalogClassType}/${this.selectData.id}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.codeInfo.thirdPartyCode = data.data ? data.data.thirdPartyCode : ''
          this.codeInfo.codeDesc = data.data ? data.data.codeDesc : ''
          this.codeForm.thirdPartyCode = data.data ? data.data.thirdPartyCode : ''
          this.codeForm.codeDesc = data.data ? data.data.codeDesc : ''
        } else {
          this.$message('获取字典数据信息失败！')
        }
      })
    },
    getLastCode() {
      this.$ajax({
        url: this.$ajax.setUrl(`pac/latest/${this.catalogClassType}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.codeInfo.lastCode = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    deleteCode() {
      this.$confirm('确定删除第三方编码？').then(() => {
        let messageBox = document.getElementsByClassName('el-message-box__wrapper')
        messageBox[0].focus() // 防止按空格键重复确定
        this.$ajax({
          url: this.$ajax.setUrl(`pac/${this.catalogClassType}/${this.selectData.id}`),
          method: 'delete',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.getThirdCode()
            this.$message.success(data.msg)
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      })
    },
    handleDownload() {
      this.$ajax({
        url: this.$ajax.setUrl('stg/stgStdFile/import/tmpl'),
        method: 'get',
        params: this.$ajax.setParams({
          tmplId: 3
        })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.$dlFile(data.data.fileId)
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    handleImport() {
      this.$refs.categoryImport.showDrawer()
    },
    resetSelect() {
      this.selectData = {
        id: '',
        pid: '',
        level: 1,
        isLeaf: true,
        sys: false,
        name: '',
        cmntStr: ''
      }
      this.editForm = {
        edit: false,
        name: '',
        cmntStr: ''
      }
      this.$refs.editForm && this.$refs.editForm.clearValidate()
    },
    beforeClose() {
      var close = true
      var msg = ''

      if (close) {
        this.drawerVisible = false
      } else {
        this.$confirm(msg)
          .then(() => {
            this.drawerVisible = false
          })
          .catch(() => {})
      }
    },
    clearDialog() {
      this.id = ''
      this.name = ''
      this.dataList = []
      this.dataIds = {}
      this.rootId = ''
      this.search = ''
      this.loading = false
      this.codeInfo.thirdPartyCode = ''
      this.codeInfo.codeDesc = ''
      this.codeInfo.lastCode = ''
      this.codeForm.thirdPartyCode = ''
      this.codeForm.codeDesc = ''
      this.resetSelect()
    },
    cancelEditCode() {
      this.codeForm.thirdPartyCode = this.codeInfo.thirdPartyCode
      this.codeForm.codeDesc = this.codeInfo.codeDesc
      this.codeEditable = false
      this.$nextTick(() => this.$refs.codeForm.clearValidate())
    }
  }
}
</script>

<style lang="scss">
.catalog-category-drawer.tag-drawer .el-drawer__body {
  .drawer-content {
    padding-bottom: 0;
    .el-form .el-form-item__label {
      font-size: 14px;
      font-weight: normal;
    }
  }
  .category-tree {
    height: 100%;
    border-right: 1px solid $border-color;
    position: relative;
    .el-input {
      width: 100%;
    }
    .el-icon-close {
      cursor: pointer;
    }
    .refresh-box {
      height: 40px;
      line-height: 40px;
      text-align: center;
      font-size: 18px;
      .el-icon-refresh {
        cursor: pointer;
      }
    }
    .category-tree-content {
      position: absolute;
      top: 50px;
      right: 0;
      bottom: 20px;
      left: 0;
    }
    .el-tree {
      margin: 10px 0;
      max-height: 100%;
      overflow: auto;
      .el-tree-node__content {
        height: 30px;
      }
      .category-tree-item {
        line-height: 30px;
        width: calc(100% - 24px);
        .category-name {
          float: left;
          max-width: calc(100% - 80px);
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .asset-count {
          float: left;
          margin-left: 20px;
          color: #2f54eb;
        }
        .tree-button {
          display: none;
          float: right;
          height: 30px;
          i {
            font-size: 16px;
            margin-right: 12px;
            line-height: inherit;
            cursor: pointer;
          }
          .el-icon-circle-plus-outline {
            color: #2f54eb;
          }
          .el-icon-delete {
            color: #f47d7d;
          }
        }
        &:hover,
        &.select {
          .tree-button {
            display: block;
          }
        }
      }
    }
    .catalog-tree-button {
      position: absolute;
      left: 20px;
      bottom: 0;
    }
  }

  .category-edit {
    position: relative;
    height: 100%;
    padding-left: 20px;
    .catalog-tip {
      font-size: 12px;
      line-height: 18px;
      color: #f56c6c;
    }
    .el-form {
      max-height: 100%;
      overflow-y: auto;
      overflow-x: hidden;
      .editForm-box {
        position: relative;
        border: 1px dashed #a8a8a8;
        border-radius: 4px;
        padding-top: 14px;
        margin-bottom: 14px;
        overflow: hidden;
        .edit-box {
          position: absolute;
          top: 0;
          right: 0;
          width: 20px;
          height: 20px;
          text-align: center;
          line-height: 20px;
          background-color: #7c7c7c;
          border-bottom-left-radius: 6px;
          color: #ffc35c;
          cursor: pointer;
        }
        .edit-button {
          text-align: right;
          padding-right: 20px;
          margin-bottom: 14px;
        }
      }
    }
    .catalog-edit-button {
      position: absolute;
      right: 20px;
      bottom: 0;
      text-align: right;
    }
  }
  .code-wrap {
    padding: 25px 20px;
    border: 1px dotted $border-color;
    position: relative;
  }
  .code-btn {
    position: absolute;
    top: 0;
    right: 0;
    width: 50px;
    height: 20px;
    text-align: center;
    line-height: 20px;
    background-color: #7c7c7c;
    border-bottom-left-radius: 6px;
    cursor: pointer;
    .edit-btn {
      width: 20px;
      margin-right: 5px;
      color: #ffc35c;
    }
    .delete-btn {
      width: 20px;
      color: #87cefa;
    }
  }
  .el-icon-info {
    margin-left: 5px;
  }
}
</style>
